package com.dssingleton;

import java.io.Serializable;

public class Dcl implements Serializable {

    private static final long serialVersionUID = 1L;

    // volatile 防止new Dcl()指令重排，导致其他线程获取到未初始化完成的实例
    private volatile static Dcl instance;

    private Dcl() {
    }

    public static Dcl getInstance() {
        // 内存地址可能先分配，但是还未初始化完成
        if (instance == null) {
            synchronized (Dcl.class) {
                if (instance == null) {
                    /**
                     *     NEW com/dssingleton/Dcl
                     *     // 内存分配和对象初始化 可能重排
                     *     INVOKESPECIAL com/dssingleton/Dcl.<init> ()V
                     *     PUTSTATIC com/dssingleton/Dcl.instance : Lcom/dssingleton/Dcl;
                     */
                    instance = new Dcl();
                }
            }
        }
        return instance;
    }

    // 反序列化时确保单例
    private Object readResolve() {
        return getInstance();
    }

}
